package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.service.factories.imp;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.command.BitCommand;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.command.BitRegisterCommand;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.command.CoilCommand;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.factories.DeviceManagerFactory;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.AddressType;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.Device;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.SimpleCommand;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.service.SimpleCommandService;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.service.factories.SimpleCommandServiceFactory;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.service.imp.SimpleCommandServiceImp;

@Component
public class SimpleCommandServiceFactoryImp implements
		SimpleCommandServiceFactory {

	@Autowired(required = true)
	private DeviceManagerFactory devman;
	
	@Override
	public List<SimpleCommandService> create(
			List<SimpleCommand> commands,Device device) {
		List<SimpleCommandService> ret = new ArrayList<SimpleCommandService>();
		for (SimpleCommand scmd : commands) {
			
			ret.add(create(scmd,device));
		}
		return ret;
	}

	@Override
	public SimpleCommandService create(SimpleCommand scmd, Device device) {
		SimpleCommandServiceImp nser = new SimpleCommandServiceImp();
		nser.setSmpcmd(scmd);
		nser.setDevman(devman.create(device));
		BitCommand cmd;
		if(scmd.getAddressType() == AddressType.HOLDING_REGISTER){
			 cmd = new BitRegisterCommand();
			((BitRegisterCommand)cmd).setAddress(scmd.getAddress());
			((BitRegisterCommand)cmd).setOffset(scmd.getBitOffset());
			
		}
		else{
			cmd = new CoilCommand();
			((CoilCommand)cmd).setAddress(scmd.getAddress());
		}
		nser.setCmd(cmd);
		return nser;
	}

	/**
	 * @return the devman
	 */
	public DeviceManagerFactory getDevman() {
		return devman;
	}

	/**
	 * @param devman the devman to set
	 */
	public void setDevman(DeviceManagerFactory devman) {
		this.devman = devman;
	}

}
